﻿using System.IO;
using System.Web;
using System.Web.Script.Serialization;
/// <summary>
/// 上传基础处理类
/// lyh
/// 2014-10-27
/// </summary>
public abstract class UploadBaseHandler:IHttpHandler
{
    protected HttpContext Context;
    protected HttpRequest Request;
    protected HttpResponse Response;

    public bool IsReusable
    {
        get { return true;}
    }

    protected int MaxFieSize = 0;
    protected string AllowedExtensions = ".jpg,.jpeg,.png,.gif,.bmp";

    public void ProcessRequest(HttpContext context)
    {
        Context = context;
        Request = context.Request;
        Response = context.Response;

        if (Request.Files.Count < 1) return;

        var file = Request.Files[0];
        var fileName = Request["name"];
        fileName = Path.GetFileName(fileName);
        var ext = Path.GetExtension(fileName);

        if (string.IsNullOrWhiteSpace(ext) || !AllowedExtensions.Contains(ext))
        {
            var result = new Result
            {
                StatusCode = 500,
                Title = "文件扩展名错误。 ",
                Message = string.Format("文件: {0}, 有效扩展名: {1}", fileName, AllowedExtensions)
            };
            WriteResponse(result);
            return;
        }

        var tstr = Request["chunks"] ?? string.Empty;
        var chunks = -1;
        if (!int.TryParse(tstr, out chunks)) chunks = -1;
        tstr = Request["chunk"] ?? string.Empty;
        var chunk = -1;
        if (!int.TryParse(tstr, out chunk)) chunk = -1;

        if (chunks == 1)
        {
            if (MaxFieSize == 0 || Request.ContentLength <= MaxFieSize)
            {
                if (!OnUploadChunk(file.InputStream, chunk, chunks, fileName)) return;
            }
            else
            {
                var result = new Result()
                {
                    StatusCode = 413,
                    Title = "文件大小错误。",
                    Message = string.Format("文件: {0}, 大小: {1}, 最大文件大小: {2}", fileName, Request.ContentLength, MaxFieSize)
                };
                WriteResponse(result);
                return;
            }
        }
        else
        {
            if (chunk == 0 && MaxFieSize > 0 && Request.ContentLength*(chunks - 1) > MaxFieSize)
            {
                var result = new Result()
                {
                    StatusCode = 413,
                    Title = "文件大小错误。",
                    Message = string.Format("文件: {0}, 最大文件大小: {1}", fileName, MaxFieSize)
                };
                WriteResponse(result);
                return;
            }
            if (!OnUploadChunk(file.InputStream, chunk, chunks, fileName)) return;
        }
        var sucess = new Result
        {
            StatusCode = 200,
            Message = "上传成功"
        };
        WriteResponse(sucess);
    }

    protected virtual bool OnUploadChunk(Stream chunkStream, int chunk, int chunks, string fileName)
    {
        return true;
    }

    protected void WriteResponse(Result result)
    {
        Response.ContentType = result.ContentType;
        Response.StatusCode = result.StatusCode;
        var json = JsonEncode(result);
        Response.Write(json);
    }

    protected string JsonEncode(object value)
    {
        var ser = new JavaScriptSerializer();
        return ser.Serialize(value);
    }
}